package pacs_server

import (
	"encoding/json"
	"errors"
	"github.com/sirupsen/logrus"

	nested "github.com/antonfisher/nested-logrus-formatter"
	"os"
	"path"
	"path/filepath"
)

func NewPacsDbManager(dbFile string, enableLog bool) (dm *PacsManager, err error) {
	dm = &PacsManager{}
	err = dm.init(dbFile, enableLog)
	return dm, err
}

func (dm *PacsManager) init(dbFile string, enableLog bool) (err error) {
	dbFile, _ = filepath.Abs(dbFile)
	if enableLog {
		logger := logrus.New()
		logger.SetFormatter(&nested.Formatter{
			FieldsOrder:     []string{"module", "msg"},
			TimestampFormat: "20060102T150405",
			HideKeys:        true,
			NoColors:        true,
		})
		logger.SetLevel(logrus.TraceLevel)
		dm.logger = logger.WithField("module", "PACS")
	}
	dm.Log("pacs manager set database:", dbFile)
	if _, err = os.Stat(path.Dir(dbFile)); err != nil {
		if err = os.MkdirAll(path.Dir(dbFile), os.ModePerm); err != nil {
			return err
		}
	} else if err = LoadDbFile(dbFile); err != nil {
		return err
	}

	dm.tableServerList = "pacs_server_list"
	return nil
}

func (dm *PacsManager) GetServer(serverName string) (pi *PacsServer, err error) {
	data, err := dm.GetServerAll()
	if err != nil {
		return nil, err
	}

	for _, pdata := range data {
		if pdata.ServerName == serverName {

			cache := pdata.CacheRoot
			if cache == "" {
				cache = "cache"
			}

			if cache, err = filepath.Abs(cache); err != nil {
				dm.Log("E get server cache folder:", err.Error())
				return &pdata, err
			} else if _, err = os.Stat(cache); err != nil {
				os.MkdirAll(cache, os.ModePerm)
			}

			//fmt.Println("pacs manager found server:", si.ServerHost, si.ServerType, cache)
			pdata.Init("PBGE", dm.logger != nil)
			return &pdata, nil
		}
	}
	return nil, errors.New("server not found")
}
func (dm *PacsManager) GetServerAll() (data []PacsServer, err error) {
	records, err := DB().Table(dm.tableServerList).Get()
	if err != nil {
		return nil, err
	}

	bs, _ := json.Marshal(records)
	err = json.Unmarshal(bs, &data)

	if err != nil {
		return nil, err
	} else {
		return data, nil
	}
}
func (dm *PacsManager) GetServerNameAll() (names []string) {
	data, err := dm.GetServerAll()
	if err != nil {
		return nil
	}

	names = make([]string, 0)

	for _, d := range data {
		names = append(names, d.ServerName)
	}
	return names
}

func (dm *PacsManager) Log(msg ...interface{}) {
	if dm.logger != nil {
		dm.logger.Print(msg...)
	}
}
